package edu.nf.ch01.common;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import java.io.InputStream;

/**
 * @author wangl
 * @date 2025/9/4
 *
 * Minio工具类
 */
public class MinioUtils {
    //连接属性
    private static final String HOST = "http://127.0.0.1:9000";
    private static final String ACCOUNT = "minioadmin";
    private static final String PASSWORD = "minioadmin";
    //Minio客户端
    private static MinioClient client;

    /**
     * 初始化客户端
     */
    static {
        client = MinioClient.builder()
                .endpoint(HOST)
                .credentials(ACCOUNT, PASSWORD)
                .build();
    }

    /**
     * 判断桶是否创建
     * @param bucketName
     * @return
     */
    public static boolean hasBucket(String bucketName) {
        try {
            return client.bucketExists(BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建桶
     * @param bucketName
     */
    public static void createBucket(String bucketName) {
        try {
            client.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        }catch (Exception e) {
            throw new RuntimeException("Create fail.", e);
        }
    }

    /**
     * 上传
     */
    public static void upload(String bucketName,
                              String objectPath,
                              String contentType,
                              long size,
                              InputStream input) {
        try {
            client.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectPath)
                    .contentType(contentType)
                    .stream(input, size, -1)
                    .build());
        }catch (Exception e) {
            throw new RuntimeException("Upload fail.", e);
        }
    }
}